<template>
  <div class="cart">
    <!-- 购物车为空时占位信息 -->
    <div v-if="cart.length==0" class="noCart">
        <div style="width:80%;display:flex;justify-content: center;align-items: center;flex-direction: column;">
            <img src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2Fa4064bdab5f6c800ed664014f3eb7d13a4dd25b3138d0-hYHe07_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1671428866&t=6023ee6a3f8d771af97ebf4bb55f82dc" 
            style="width:30%"
            alt="">
            <div>你购物车里什么都没有哦</div>
            <a href="/mall/category" style="display:block">去逛逛</a>
        </div>
    </div>

    <!-- 购物车不为空时 -->
    <div class="myCart" v-if="cart.length!=0">
        <!-- 购物车顶部信息 -->
        <div class="top">
            <div class="top_left">
                <div style="font-size:1.8vw">购物车(全部<span style="font-size:2vw;color:red">{{ totalNumber }}</span>)</div>
            </div>
            <div class="top_right">
                <span style="font-size:1.5vw">已选商品(不含运费):￥<span style="font-size:1.9vw;color:red;margin-left: 5px;">{{ totalPrice }}</span></span>
                <div @click="confirm">结算</div>
            </div>
            <el-dialog title="请填写订单信息" :visible.sync="orderFormVisible">
                <el-form :model="orderForm">
                    <el-form-item label="收货地址" :label-width="formLabelWidth" style="margin-left:-20px">
                        <el-select v-model="orderForm.address" placeholder="请填写收货地址">
                            <el-option 
                            :label="item.province+'-'+item.address+'-'+item.name+'-'+item.phoneNumber" 
                            :value="item.province+'-'+item.address+'-'+item.name+'-'+item.phoneNumber" 
                            v-for="(item,index) in addressList" 
                            :key="index"
                            style="padding-left:5px"
                            ></el-option>
                            <!-- <el-option label="区域二" value="beijing"></el-option> -->
                        </el-select>
                    </el-form-item>
                </el-form>
                <div style="display:flex;width:85%;justify-content:space-between;margin-left:32px;">
                    <div style="margin-top:5px;display:flex;justify-content: left;align-items:center">订单信息</div>
                    <div style="color:red;font-size:1.6vw;display:flex;justify-content: right;align-items: center;">总金额:   ￥{{ confirmTotalPrice }}</div>
                </div>
                
                <div class="order_list" style="width:85%;min-height: 200px;display: flex;flex-direction: column;margin-top: 10px;margin-left:32px;overflow: auto;">
                    <div style="width:100%;display:flex;justify-content: space-between;margin-bottom: 10px;padding-bottom:3%;border-bottom: 1px solid #999;"
                    v-for="(item,index) in confirmCart" :key="index"
                    >
                        <div style="width:20%;display: flex;justify-content: left;align-items: center">
                            <img :src="item.src" alt="" style="width:90%;">
                        </div>
                        <div style="width:35%;display: flex;justify-content: center;align-items: center;">{{ item.name }}</div>
                        <div style="width:10%;display: flex;justify-content: center;align-items: center;">X{{ item.number }}</div>
                        <div style="width:15%;display: flex;justify-content: center;align-items: center;">￥{{ item.number*item.price }}</div>
                    </div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button size="medium" @click="orderFormVisible = false">取消支付</el-button>
                    <el-button size="medium" type="primary" @click="fun">确定支付</el-button>
                </div>
            </el-dialog>
        </div>

        <!-- 购物车主体信息 -->
        <div class="main">
            <!-- 产品列表头部 -->
            <div class="list_top">
                <div style="width:3.95vw;height: 3.29vw;line-height: 3.29vw;">
                    <el-checkbox v-model="allChecked" @change="allStateChange">全选</el-checkbox>
                    <!-- <el-checkbox v-model="test">测试</el-checkbox> -->
                </div>
                <div style="width:32.91vw;height: 3.29vw;line-height: 3.29vw;text-align: center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
                    商品信息
                </div>
                <div style="width:9.21vw;height: 3.29vw;line-height: 3.29vw; text-align: center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
                    单价
                </div>
                <div style="width:9.21vw;height: 3.29vw;line-height: 3.29vw;text-align: center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis">
                    数量
                </div>
                <div style="width:9.21vw;height: 3.29vw;line-height: 3.29vw;text-align: center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis">
                    金额
                </div>
                <div style="width:10.53vw;height: 3.29vw;line-height: 3.29vw;text-align: center;">
                    操作
                </div>
            </div>
            <!-- 产品列表 -->
            <div class="cart_list">
                <div class="cart_item" v-for="(item,index) in cart" :key="index">
                    <div style="width:3.95vw;height: 6.59vw;line-height: 6.59vw; text-align: center;">
                        <el-checkbox v-model="item.checked" @change="stateChange(index)"></el-checkbox>
                    </div>
                    <div style="width:32.91vw;height: 6.59vw;line-height: 6.59vw;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;margin-left:1.65vw">
                        <img :src="item.src" alt="" style="width:6.59vw">
                        <span style="font-size:1.6vw;position: relative;top: -40px;left: 5px;">{{ item.name }}</span>
                    </div>
                    <div style="width:9.21vw;height:  6.59vw;line-height:6.59vw; text-align: center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;">
                        ￥{{ item.price }}
                    </div>
                    <div style="width:9.21vw;height:  6.59vw;line-height: 6.59vw; text-align: center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis">
                        <button style="width:2vw;height: 2vw;font-size: 1.8vw;" @click="decrease(index)">-</button>
                        <span style="display: inline-block;text-align: center;min-width:1.92vw;font-size:1.8vw;">{{item.number}}</span>
                        <button style="width:2vw;height: 2vw;font-size: 1.8vw;" @click="add(index)">+</button>
                    </div>
                    <div style="width:10.53vw;height: 6.59vw;line-height: 6.59vw; text-align: center;color:orangered;overflow: hidden;white-space: nowrap;text-overflow: ellipsis">
                        ￥{{ item.price * item.number }}   
                    </div>
                    <div style="width:10.53vw;height: 6.59vw;line-height: 6.59vw; text-align: center;overflow: hidden;white-space: nowrap;text-overflow: ellipsis">
                        <el-popconfirm
                            style="margin-left: 5px;font-size: 1.8vw;"
                            confirm-button-text='确定'
                            cancel-button-text='我再想想'
                            icon="el-icon-info"
                            icon-color="red"
                            title="您确定将此商品移除购物车吗？"
                            @confirm="handleDelete(index)"
                        >
                            <el-button type="danger" slot="reference">删除 <i class="el-icon-delete"></i></el-button>
                        </el-popconfirm>
                    </div>
                </div>
                
            </div>
        </div>
    </div>
  </div>
</template>

<script>
import { getUserId } from '@/utils/getUserId'
export default {
    data(){
        return{
            totalNumber:0,
            totalPrice:0,
            cart:[],
            confirmCart:[],
            confirmTotalPrice:0,
            test:false,
            allChecked:false,
            checked:false,
            // 提交订单
            orderFormVisible:false,
            orderForm:{},
            formLabelWidth: '120px',
            addressList:[],
            payForm:{},
            flagx:0,
            flagy:0,
            userId:0
        }
    },
    methods:{
        async load(){
            this.totalNumber=0
            this.totalPrice=0
            this.cart=localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) :[]
            this.allChecked=this.cart.every(item=>item.checked==true)
            for(let i=0;i<this.cart.length;i++){
                if(this.cart[i].checked){
                    this.totalNumber++
                    this.totalPrice +=this.cart[i].price*this.cart[i].number
                }
            }


            let token=JSON.parse(sessionStorage.getItem('user')).token
            this.userId=getUserId(token)
            
        },
        // 检测用户买这个商品是否厂库有库存
        async verifyStock(goodsId,quantity){
            let res=await this.request.get('/goods/'+`${goodsId}`)
            if(res.data){
                console.log('查询库存请求成功:',goodsId);
                if(res.data.goodsStock-quantity>0){
                    res['state']=true
                    console.log('库存充足:',goodsId);
                }else{
                    console.log('库存不足，购买失败');
                    res['state']=false
                }
            }
            // console.log(res.state);
            return res.state
        },
        async fun(){
            if(this.orderForm.address!=undefined){
                this.payForm={}
                let orderDetail=[]
                this.confirmCart.forEach(item=>{
                    let str=''
                    str=str+item.name+' '+'×'+' '+item.number
                    orderDetail.unshift(str)
                })
                // 订单内容对象
                this.payForm['orderId']=this.orderCode()
                this.payForm['orderUser']=this.userId
                this.payForm['orderDetail']=orderDetail.toString()
                this.payForm['orderAddress']=this.orderForm.address
                this.payForm['orderState']='未发货'
                this.payForm['orderPrice']=this.confirmTotalPrice
                // 数据库商品数量加减、生成订单之前先查查还有没有商品库存
                this.flagx=0
                for(let i=0;i<this.confirmCart.length;i++){
                    let state=await this.verifyStock(this.confirmCart[i].goodsId,this.confirmCart[i].number)
                    if(state){
                        this.flagx++
                    }else{
                        this.$message.warning('这个产品库存不足:',this.confirmCart[i].goodsName);
                    }
                }   
                console.log('循环结束',this.flagx); 
                // 商品库存都还有，数据库做加减
                if(this.flagx==this.confirmCart.length){
                    this.flagy=0
                    for(let i=0;i<this.confirmCart.length;i++){
                        let goodsForm={}
                        let res1=await this.request.get('/goods/'+`${this.confirmCart[i].goodsId}`)
                        if(res1.data){
                            goodsForm=res1.data;
                            goodsForm.goodsSold=goodsForm.goodsSold+this.confirmCart[i].number
                            goodsForm.goodsStock=goodsForm.goodsStock-this.confirmCart[i].number
                        }else{
                            console.log('商品查询不到');
                        }
                        let res2=await this.request.post("/goods",goodsForm)
                        if(res2.data){
                            this.flagy++
                            console.log('库存数量修改成功');
                        }else{
                            this.$message.error("库存数量修改失败！")
                        } 
                    }
                    // 数据库减完之后生成订单
                    if(this.flagy==this.confirmCart.length){
                        let res=await this.request.post("/order",this.payForm)
                        if(res.data){
                            this.$message.success("下单成功！")
                            this.cart=this.cart.filter(item=>item.checked!=true)
                            localStorage.setItem('cart',JSON.stringify(this.cart))
                            this.orderFormVisible=false
                            this.load()
                        }else{
                            this.$message.error("订单生成失败！")
                            this.orderFormVisible=false
                        }
                    }
                }          
            }else{
                this.$message.warning('还未填写收货地址~~')
            }
        },






















      
        // 全选与全不选
        allStateChange(){
            if(this.allChecked==true){
                this.totalNumber=this.cart.length
                for(let i=0;i<this.cart.length;i++){
                    this.totalPrice=this.totalPrice+this.cart[i].number*this.cart[i].price
                }
                const newArray=this.cart.map(function(item,index){
                    item.checked=true
                    return item
                })
                this.cart=newArray
                localStorage.setItem('cart',JSON.stringify(this.cart))
                this.load()
                // console.log(newArray);
                
            }else{
                this.totalNumber=0
                this.totalPrice=0
                const newArray=this.cart.map(function(item,index){
                    item.checked=false
                    return item
                })
                this.cart=newArray
                // for(let i=0;i<this.cart.length;i++){
                //     this.cart[i].checked=false
                // }
                localStorage.setItem('cart',JSON.stringify(this.cart))
                this.load()
            }
        },
        // 普通复选按钮
        stateChange(index){
            // console.log(this.checked);
            this.checked=!this.checked
            this.cart[index].checked=this.checked
            this.allChecked=this.cart.every(item=>item.checked==true)
            localStorage.setItem('cart',JSON.stringify(this.cart))
            this.load()
        },
        
        //#region (购物车表单里的数量加减按钮)
        decrease(index){
            this.cart[index].number--
            if(this.cart[index].number<1){
                this.$message.warning('最少只能购买一件~')
                this.cart[index].number=1
            }
            localStorage.setItem('cart',JSON.stringify(this.cart))
            this.load()
        },
        add(index){
            this.cart[index].number++
            localStorage.setItem('cart',JSON.stringify(this.cart))
            this.load()
        },
        //#endregion



        //点击删除按钮触发事件
        handleDelete(index){
            this.cart.splice(index)
            localStorage.setItem('cart',JSON.stringify(this.cart))
            this.load()
        },
        // 点击结算按钮
        confirm(){
            this.confirmTotalPrice=0
            this.confirmCart=[]
            this.cart.forEach((item)=>{
                if(item.checked){
                    this.confirmTotalPrice+=item.number*item.price
                    this.confirmCart.unshift(item)
                }
                // return this.confirmCart
            })
            if(this.confirmCart.length==0){
                this.$message.warning('还没有选中商品呢~~~')
            }else{
                this.orderFormVisible=true
            }
            
            console.log('结算:',this.confirmCart);
        },
        // 确定支付
        surePay(){
            if(this.orderForm.address!=undefined){
                this.payForm={}
                let orderDetail=[]
                this.confirmCart.forEach(item=>{
                    let str=''
                    str=str+item.name+' '+'×'+' '+item.number
                    orderDetail.unshift(str)
                })
                this.payForm['orderId']=this.orderCode()
                this.payForm['orderUser']=JSON.parse(localStorage.getItem('user')).id
                this.payForm['orderDetail']=JSON.stringify(orderDetail)
                this.payForm['orderAddress']=this.orderForm.address
                this.payForm['orderState']='未发货'
                this.payForm['orderPrice']=this.confirmTotalPrice
                // console.log(this.payForm);
                this.flag=0
                this.confirmCart.forEach(item=>{
                    let goodsForm={}
                    new Promise((resolve,reject)=>{
                        // 先把要购买的商品查询一下后台还有没有足够的存货
                        this.request.get('/goods/'+`${item.goodsId}`).then(res=>{
                            if(res.data){
                                goodsForm=res.data;
                                if(goodsForm.goodsStock-item.number>0){
                                    goodsForm.goodsStock=goodsForm.goodsStock-item.number
                                    resolve(goodsForm)
                                }else{
                                    this.$message.warning('sorry啊,该商品已被抢夺一空~~')
                                }
                            }
                        })
                    }).then(data=>{
                        // console.log('data:',data);
                        new Promise((resolve,reject)=>{
                             // 库存足够，后台做商品数量减法
                            this.request.post("/goods",data).then(res=>{
                                if(res.data){
                                    console.log('数量已经被减');
                                    this.flag++
                                    resolve(this.flag)
                                }else{
                                    this.$message.error("商品库存不足~~~！")
                                }
                            })
                        }).then(data2=>{
                            if(data2==this.confirmCart.length){
                                // 后台商品数量减法完之后，生成订单
                                this.request.post("/order",this.payForm).then(res=>{
                                    if(res.data){
                                        this.$message.success("下单成功！")
                                        this.cart=this.cart.filter(item=>item.checked!=true)
                                        localStorage.setItem('cart',JSON.stringify(this.cart))
                                        this.orderFormVisible=false
                                        this.load()
                                    }else{
                                        this.$message.error("下单失败！")
                                        this.orderFormVisible=false
                                    }
                                })
                            }
                        })
                    })
                })
            }else{
                this.$message.warning('还未填写收货地址~~')
            }
        },
        
        // 生成订单编号
        orderCode(){
            var orderCode='';
            for (var i = 0; i < 6; i++) //6位随机数，用以加在时间戳后面。
            {
                orderCode += Math.floor(Math.random() * 10);
            }
            orderCode = 'gh'+new Date().getTime() + orderCode;  //时间戳，用来生成订单号。
            console.log(orderCode)
            return orderCode
        },
    },
    mounted(){
        this.addressList=localStorage.getItem('address_list')?JSON.parse(localStorage.getItem('address_list')):[]
        this.load()
    }
}
</script>

<style scoped>
*{
    margin: 0;
    padding: 0;
}
.cart{
    width: 100%;
    display: flex;
    background-color: rgb(233,229,229);
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.noCart{
    margin-top: 10px;
    margin-bottom: 10px;
    width: 80%;
    min-height: 380px;
    background-color: white;
    border-radius: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.myCart{
    margin-top: 10px;
    margin-bottom: 10px;
    width: 80%;
    min-height: 380px;
    background-color: white;
    border-radius: 20px;
}
/* 购物车头部 */
.top{
    display: flex;
    flex-direction:row ;
    justify-content: space-between;
    width: 100%;
    height: 80px;
    
    border-bottom: 1px solid #999;
}
.top_left{
    margin-left: 15px;
    width: 200px;
    height: 80px;
    line-height: 80px;
    font-size: 25px;
}
.top_right{
    margin-right: 10px;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
}
.top_right div{
    margin-left: 3.29vw;
    font-size: 1.6vw;
    width:4.94vw;
    height: 2.96vw;
    line-height: 2.96vw;
    background-color: orangered;
    border-radius: 1.8vw;
    text-align: center;
    color:white;
    cursor: pointer;
}
.main{
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.list_top{
    width: 96%;
    height: 50px;
    display: flex;
}
.cart_list{
    width: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding-bottom: 10px;
}
.cart_item{
    /* box-sizing: border-box; */
    margin-top: 10px;
    width:100% ;
    height: 110px;
    /* border-radius: 15px; */
    /* background-color: rgb(245,245,245); */
    display: flex;
    border-bottom: 1px solid #999;
    padding-bottom: 10px;
}
</style>